package top.jiangqiang.qianyi.common.filter;

import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import top.jiangqiang.qianyi.common.constants.GlobalConstants;
import top.jiangqiang.qianyi.common.filter.caching.CachingFilter;
import top.jiangqiang.qianyi.common.filter.logging.RequestLoggingFilter;
import top.jiangqiang.qianyi.common.filter.xss.XssFilter;
import top.jiangqiang.qianyi.common.properties.FilterProperties;

@Configuration
@Slf4j
public class FilterAutoConfiguration {
    @Bean
    CachingFilter cachingFilter(FilterProperties filterProperties) {
        FilterProperties.CachingProperties properties = filterProperties.getCaching();
        return new CachingFilter(properties.getIncludePatterns(), properties.getOrder(), properties.getExcludePatterns(), properties.getMaxCacheBodyLength());
    }

    @ConditionalOnProperty(prefix = GlobalConstants.GLOBAL_PREFIX + ".filter.logging", name = "enabled", havingValue = "true", matchIfMissing = true)
    @Bean
    RequestLoggingFilter loggingFilter(FilterProperties filterProperties) {
        FilterProperties.LoggingProperties properties = filterProperties.getLogging();
        RequestLoggingFilter loggingFilter = new RequestLoggingFilter(properties.getIncludePatterns(), properties.getOrder(), properties.getExcludePatterns());
        loggingFilter.setMaxPrintBodyLength(properties.getMaxPrintBodyLength());
        FilterProperties.LoggingProperties.LogLevel level = properties.getLevel();
        switch (level) {
            case BASIC_HEADER -> {
                loggingFilter.setLogRequestHeaders(true);
                log.info(level.getDesc());
            }
            case BASIC_BODY -> {
                loggingFilter.setLogRequestBody(true);
                log.info(level.getDesc());
            }
            case ALL -> {
                loggingFilter.setLogRequestHeaders(true);
                loggingFilter.setLogRequestBody(true);
                log.info(level.getDesc());
            }
            default -> log.info(level.getDesc());
        }
        return loggingFilter;
    }

    @ConditionalOnProperty(prefix = GlobalConstants.GLOBAL_PREFIX + ".filter.xss", name = "enabled", havingValue = "true", matchIfMissing = true)
    @Bean
    XssFilter xssFilter(FilterProperties filterProperties) {
        FilterProperties.XssProperties properties = filterProperties.getXss();
        return new XssFilter(properties.getIncludePatterns(), properties.getOrder(), properties.getExcludePatterns());
    }
}
